﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Data.Linq;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using FukiERP.Services.DBContext;
using FukiERP.Services.Helper;
using FukiERP.Common.Constants;
using FukiERP.Helper;
using Telerik.WinControls;
using Telerik.WinControls.UI;

namespace FukiERP.Product
{
    public partial class frm_ProductCategory : Telerik.WinControls.UI.RadForm
    {
        private string _productCateTreeNameParttern = "{0} ({1})";
        private int _currentCateID = 0;

        public frm_ProductCategory()
        {
            InitializeComponent();
        }

        private void frm_ProductCategory_Load(object sender, EventArgs e) {
            LoadProductCateTree();
        }

        private void LoadProductCateTree() {
            FukiERPDataContext context = DataAccess.GetDBContext();
            List<ProductCategory> cates = context.ProductCategories.ToList();
            List<RadTreeNode> parentNode = cates.Where(x => x.Parent == 0).OrderBy(x => x.Order).
                Select(x => new RadTreeNode(string.Format(_productCateTreeNameParttern,x.Name, x.Order)) { Value = x}).ToList();
            trv_ProductCateList.Nodes.AddRange(parentNode);
            foreach (RadTreeNode node in trv_ProductCateList.Nodes) {
                BuildChildNode(node, cates);
            }
            trv_ProductCateList.Nodes.Insert(0, (new RadTreeNode(CommonConstants.NoneValue) 
                { Value = new ProductCategory() { ID = 0, Name = CommonConstants.NoneValue } }));
            trv_ProductCateList.Nodes.First().Selected = true;
            trv_ProductCateList.DisplayMember = ColumName.Col_Name;
            trv_ProductCateList.ValueMember = ColumName.Col_ID;
            trv_ProductCateList.ExpandAll();
        }

        private void BuildChildNode(RadTreeNode node, List<ProductCategory> cates) {
            List<RadTreeNode> nodeList = cates.Where(x => x.Parent == ((ProductCategory) node.Value).ID).OrderBy(x => x.Order).
                Select(x => new RadTreeNode(string.Format(_productCateTreeNameParttern, x.Name, x.Order)) { Value = x }).ToList();
            if (nodeList.Count() != 0) {
                node.Nodes.AddRange(nodeList);
                foreach (RadTreeNode childNode in nodeList) {
                    BuildChildNode(childNode, cates);
                }
            }
        }

        private void tbn_Save_Click(object sender, EventArgs e) {
            errorProvider1.Clear();
            bool isValid = ValidateValue.ValidateRequirement(errorProvider1, tbx_ProCateName);
            isValid = isValid && ValidateValue.ValidateRequirement(errorProvider1, tbx_Order);
            isValid = isValid && ValidateValue.ValidateNumber(errorProvider1, tbx_Order);
            if (!isValid) {
                MessageBox.Show(MessageConstants.GaneralValidateMessage);
                return;
            }
            ProductCategory cate = new ProductCategory();     
            FukiERPDataContext context = DataAccess.GetDBContext();
            if (_currentCateID != 0) {
                cate = context.ProductCategories.Where(c => c.ID == _currentCateID).FirstOrDefault();
                if (cate == null) {
                    return;
                }
            } else {
                cate = context.ProductCategories.Where(c => c.Name == tbx_ProCateName.Text).FirstOrDefault();
                if (cate != null) {
                    MessageBox.Show(MessageConstants.DuplicateErrorMessage);
                    return;
                }
                cate = new ProductCategory();
            }
            cate.Name = tbx_ProCateName.Text;
            cate.Order = Convert.ToInt32(tbx_Order.Text);
            cate.Description = tbx_ProCateDes.Text;
            int parentId = ((ProductCategory)trv_ProductCateList.SelectedNode.Value).ID;
            if (_currentCateID != parentId) {
                cate.Parent = parentId;
            }
            if (_currentCateID == 0) {
                context.ProductCategories.InsertOnSubmit(cate);
            }
            context.SubmitChanges();
            RefreshForm();
        }

        private void RefreshForm() {
            trv_ProductCateList.Nodes.Clear();
            LoadProductCateTree();
            if (_currentCateID == 0) {
                ClearInput();
            }
        }

        private void trv_ProductCateList_NodeMouseClick(object sender, RadTreeViewEventArgs e) {
            tbx_ParentNode.Text = ((ProductCategory) trv_ProductCateList.SelectedNode.Value).Name;
        }

        private void trv_ProductCateList_NodeMouseDoubleClick(object sender, RadTreeViewEventArgs e) {
            ProductCategory cate = (ProductCategory) trv_ProductCateList.SelectedNode.Value;
            tbx_ProCateName.Text = cate.Name;
            tbx_Order.Text = cate.Order.ToString();
            tbx_ProCateDes.Text = cate.Description;
            tbx_ParentNode.Text = trv_ProductCateList.SelectedNode.Parent == null ? string.Empty :
                (trv_ProductCateList.SelectedNode.Parent.Value as ProductCategory).Name;
            _currentCateID = cate.ID;
        }

        private void btn_Create_Click(object sender, EventArgs e) {
            _currentCateID = 0;
            ClearInput();
        }

        private void ClearInput() {
            tbx_ProCateName.Text = string.Empty;
            tbx_Order.Text = string.Empty;
            tbx_ProCateDes.Text = string.Empty;
            tbx_ParentNode.Text = string.Empty;
        }

        private void btn_Delete_Click(object sender, EventArgs e) {
            if (_currentCateID != 0) {
                FukiERPDataContext context = DataAccess.GetDBContext();
                context.ProductCategories.DeleteOnSubmit(context.ProductCategories.
                    Where(c => c.ID == _currentCateID).First());
                context.SubmitChanges();
                _currentCateID = 0;
                RefreshForm();
            }
        }
    }
}
